package com.fc.remoting.client;

import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

public class ClientChannelManager extends ChannelHandlerAdapter {

	private static final ConcurrentHashMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>();
	public static AttributeKey<String> ATT_IDENTITY = AttributeKey.valueOf("identity");

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		String id = channel.attr(ATT_IDENTITY).get();
		channels.remove(id);
		super.channelInactive(ctx);
	}

	public static Channel getChannel(String id) {
		return channels.get(id);
	}
	
	public static Channel getDefaultChannel(){
		return channels.get(IRemotingClient.REMOTING_CLIENT_ID);
	}

	public static void addChannel(String id, Channel channel) {
		channel.attr(ATT_IDENTITY).set(id);
		channels.putIfAbsent(id, channel);
	}
}
